package com.authine.cloudpivot.common.extension.customized.service.impl;

import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.alibaba.fastjson.JSON;

import com.authine.cloudpivot.common.extension.customized.service.DepartmentSyncService;
import com.authine.cloudpivot.common.organization.api.DepartmentServiceI;
import com.authine.cloudpivot.common.organization.api.OrganizationServiceI;
import com.authine.cloudpivot.common.organization.model.Department;
import com.authine.cloudpivot.common.organization.model.Organization;
import com.authine.cloudpivot.common.organization.model.OrganizationSourceConfig;
import com.authine.cloudpivot.common.organization.model.enums.SourceType;
import com.authine.cloudpivot.common.organization.model.enums.Status;
import com.yundasys.hrcenter.dto.PcOrganizationInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author saiwen
 * @date 2021/5/25 14:26
 * description
 */
@Service
@Slf4j
public class DepartmentSyncServiceImpl implements DepartmentSyncService {

    @Autowired
    private DepartmentServiceI departmentServiceI;
    @Autowired
    private OrganizationServiceI organizationServiceI;


    @Override
    public void syncData(PcOrganizationInfoDTO organizationInfoDTO) throws BizException {
        if (null == organizationInfoDTO) {
            log.error("部门数据为空");
            throw new BizException("部门数据为空");
        }
        String deptId = String.valueOf(organizationInfoDTO.getId());
        String name = organizationInfoDTO.getOrgName();
        String parentDeptId = organizationInfoDTO.getParentOrgId();
        Department parentDept = null;
        if (StringUtils.isNotEmpty(parentDeptId)) {
            SingleResponse<Department> response = departmentServiceI.getDepartmentById(parentDeptId);
            if(response.isSuccess() && response.getData() != null){
                parentDept = response.getData();
            }else{
                log.error("sourceId[{}]代表的父部门不存在，无法创建", parentDeptId);
                throw new BizException("未找到父部门数据");
            }
        }else{
            //不存在父部门则创建组织
            Organization organization = new Organization();
            organization.setId(deptId);
            organization.setName(name);
            organization.setStatus(Status.ENABLE);
            organization.setSourceType(SourceType.SELF_MAINTENANCE);
            organization.setSourceConfig(new OrganizationSourceConfig());
            organization.setDepartmentId(deptId);
            organizationServiceI.create(organization);
        }
        Department department;
        boolean exists = false;
        SingleResponse<Department> response = departmentServiceI.getDepartmentById(deptId);
        if (response.isSuccess() && response.getData()!=null){
            exists = true;
        }

        if (!exists) {
            log.info("准备新增部门数据");
            department = new Department();
            department.setId(deptId);
        } else {
            log.info("准备更新部门数据");
            department = response.getData();
            department.setModifiedTime(new Date());
        }
        department.setName(name);
        department.setParentId(parentDeptId);
        //如果是新的创建的的部门，部门ID就是组织ID
        department.setOrgId(StringUtils.isEmpty(parentDeptId) ? deptId : parentDept.getOrgId());
        department.setSourceId(deptId);
        department.setIsLeaf(true);
        List<String> strings = Arrays.asList(department.getOrgId(), department.getParentId(), department.getId()).stream()
                .filter(StringUtils::isNotEmpty).distinct().collect(Collectors.toList());
        department.setQueryCode(String.join("#",strings));

        SingleResponse<Department> departmentSingleResponse;
        if (exists){
            departmentSingleResponse = departmentServiceI.update(department);
        }else{
            departmentSingleResponse = departmentServiceI.create(department);
        }
        log.info("部门数据保存完成，结果为: {}", JSON.toJSONString(departmentSingleResponse));
    }


}
